<article id={elementId}
         class={className}
         tabindex="0"
         aria-posinset={index + 1}
         aria-setsize={length}
         aria-label={ariaLabel}
         on:recalculateHeight
         ref:article
>
  {#if showHeader}
    <StatusHeader {...params} />
  {/if}
  <StatusAuthorName {...params} />
  <StatusAuthorHandle {...params} />
  {#if !isStatusInOwnThread}
    <StatusRelativeDate {...params} {...timestampParams} />
  {/if}
  <StatusSidebar {...params} />
  {#if spoilerText}
    <StatusSpoiler {...params} {spoilerShown} on:recalculateHeight />
  {/if}
  {#if !showContent}
    <StatusMentions {...params} />
  {/if}
  {#if content && (showContent || preloadHiddenContent)}
    <StatusContent {...params} shown={showContent}/>
  {/if}
  <!-- Apparently it's possible for spoilered content to sometimes have embeds, but I can't figure out how.
       Don't bother optimizing this with the preloadHiddenContent. -->
  {#if showCard && showContent}
    <StatusCard {...params} />
  {/if}
  {#if showMedia }
    <StatusMediaAttachments {...params} on:recalculateHeight />
  {/if}
  {#if showPoll && (showContent || preloadHiddenContent)}
    <StatusPoll {...params} shown={showContent} on:recalculateHeight />
  {/if}
  {#if isStatusInOwnThread}
    <StatusDetails {...params} {...timestampParams} />
  {/if}
  {#if !isStatusInNotification}
    <StatusToolbar {...params} {replyShown} on:recalculateHeight on:focusArticle="focusArticle()" />
  {/if}
  {#if replyShown}
    <StatusComposeBox {...params} on:recalculateHeight />
  {/if}
</article>
{#if enableShortcuts}
  <Shortcut scope={shortcutScope} key="o" on:pressed="open()" />
  <Shortcut scope={shortcutScope} key="p" on:pressed="openAuthorProfile()" />
  <Shortcut scope={shortcutScope} key="m" on:pressed="mentionAuthor()" />
{/if}

<style>
  .status-article {
    padding: var(--status-pad-v) var(--status-pad-h);
    display: grid;
    grid-template-areas:
        "header  header       header        header"
        "sidebar author-name  author-handle relative-date"
        "sidebar spoiler      spoiler       spoiler"
        "sidebar spoiler-btn  spoiler-btn   spoiler-btn"
        "sidebar mentions     mentions      mentions"
        "sidebar content      content       content"
        "sidebar card         card          card"
        "sidebar media-grp    media-grp     media-grp"
        "sidebar poll         poll          poll"
        "media   media        media         media"
        "....... toolbar      toolbar       toolbar"
        "compose compose      compose       compose";
    grid-template-columns: min-content minmax(0, max-content) 1fr min-content;
    grid-template-rows: repeat(8, max-content);
  }

  .status-article.tap-on-status {
    cursor: pointer;
  }

  .status-article.status-in-timeline {
    border-bottom: 1px solid var(--main-border);
  }

  .status-article.status-direct {
    background-color: var(--status-direct-background);
  }

  .status-article.status-in-own-thread {
    grid-template-areas:
      "sidebar     author-name"
      "sidebar     author-handle"
      "spoiler     spoiler"
      "spoiler-btn spoiler-btn"
      "mentions    mentions"
      "content     content"
      "card        card"
      "media-grp   media-grp"
      "media       media"
      "poll        poll"
      "details     details"
      "toolbar     toolbar"
      "compose     compose";
    grid-template-columns: min-content 1fr;
    grid-template-rows: repeat(7, max-content);
  }
</style>
<script>
  import StatusSidebar from './StatusSidebar.html'
  import StatusHeader from './StatusHeader.html'
  import StatusAuthorName from './StatusAuthorName.html'
  import StatusAuthorHandle from './StatusAuthorHandle.html'
  import StatusRelativeDate from './StatusRelativeDate.html'
  import StatusDetails from './StatusDetails.html'
  import StatusCard from './StatusCard.html'
  import StatusToolbar from './StatusToolbar.html'
  import StatusMediaAttachments from './StatusMediaAttachments.html'
  import StatusContent from './StatusContent.html'
  import StatusSpoiler from './StatusSpoiler.html'
  import StatusComposeBox from './StatusComposeBox.html'
  import StatusMentions from './StatusMentions.html'
  import StatusPoll from './StatusPoll.html'
  import Shortcut from '../shortcut/Shortcut.html'
  import { store } from '../../_store/store.js'
  import { goto } from '../../../../__sapper__/client.js'
  import { registerClickDelegate } from '../../_utils/delegate.js'
  import { classname } from '../../_utils/classname.js'
  import { checkDomAncestors } from '../../_utils/checkDomAncestors.js'
  import { scheduleIdleTask } from '../../_utils/scheduleIdleTask.js'
  import { getAccountAccessibleName } from '../../_a11y/getAccountAccessibleName.js'
  import { getAccessibleLabelForStatus } from '../../_a11y/getAccessibleLabelForStatus.js'
  import { formatTimeagoDate } from '../../_intl/formatTimeagoDate.js'
  import { measureText } from '../../_utils/measureText.js'
  import { LONG_POST_LENGTH, LONG_POST_TEXT } from '../../_static/statuses.js'
  import { absoluteDateFormatter, dayOnlyAbsoluteDateFormatter } from '../../_utils/formatters.js'
  import { composeNewStatusMentioning } from '../../_actions/mention.js'
  import { createStatusOrNotificationUuid } from '../../_utils/createStatusOrNotificationUuid.js'
  import { addEmojiTooltips } from '../../_utils/addEmojiTooltips.js'
  import { tryToFocusElement } from '../../_utils/tryToFocusElement.js'

  const INPUT_TAGS = new Set(['a', 'button', 'input', 'textarea', 'label'])
  const isUserInputElement = node => INPUT_TAGS.has(node.localName)
  const isToolbar = node => node.classList.contains('status-toolbar')
  const isStatusArticle = node => node.classList.contains('status-article')

  export default {
    oncreate () {
      const { elementId, isStatusInOwnThread, showContent } = this.get()
      const { disableTapOnStatus } = this.store.get()
      if (!isStatusInOwnThread && !disableTapOnStatus) {
        // the whole <article> is clickable in this case
        registerClickDelegate(this, elementId, (e) => this.onClickOrKeydown(e))
      }
      if (!showContent) {
        scheduleIdleTask(() => {
          // Perf optimization: lazily load the StatusContent when the user is idle so that
          // it's fast when they click the "show more" button
          this.set({ preloadHiddenContent: true })
        })
      }
      scheduleIdleTask(() => addEmojiTooltips(this.refs.article))
    },
    components: {
      StatusSidebar,
      StatusHeader,
      StatusAuthorName,
      StatusAuthorHandle,
      StatusRelativeDate,
      StatusDetails,
      StatusToolbar,
      StatusMediaAttachments,
      StatusContent,
      StatusCard,
      StatusPoll,
      StatusSpoiler,
      StatusComposeBox,
      StatusMentions,
      Shortcut
    },
    data: () => ({
      notification: undefined,
      replyVisibility: undefined,
      preloadHiddenContent: false,
      enableShortcuts: null
    }),
    store: () => store,
    methods: {
      onClickOrKeydown (e) {
        const { type, keyCode, target } = e

        const isClick = type === 'click'
        const isEnter = type === 'keydown' && keyCode === 13
        if (!isClick && !isEnter) {
          return false
        }
        if (checkDomAncestors(target, isUserInputElement, isStatusArticle)) {
          // this element or any ancestors up to the status-article element is
          // a user input element
          return false
        }
        if (checkDomAncestors(target, isToolbar, isStatusArticle)) {
          // this element or any of its ancestors is the toolbar
          return false
        }

        this.open()
        return true
      },
      open () {
        const { originalStatusId } = this.get()
        goto(`/statuses/${originalStatusId}`)
      },
      openAuthorProfile () {
        const { accountForShortcut } = this.get()
        goto(`/accounts/${accountForShortcut.id}`)
      },
      async mentionAuthor () {
        const { accountForShortcut } = this.get()
        await composeNewStatusMentioning(accountForShortcut)
      },
      focusArticle () {
        const { elementId } = this.get()
        tryToFocusElement(elementId, /* scroll */ true)
      }
    },
    computed: {
      originalStatus: ({ status }) => status.reblog ? status.reblog : status,
      originalStatusId: ({ originalStatus }) => originalStatus.id,
      statusId: ({ status }) => status.id,
      notificationId: ({ notification }) => notification && notification.id,
      account: ({ notification, status }) => (
        (notification && notification.account) || status.account
      ),
      accountId: ({ account }) => account.id,
      originalAccount: ({ originalStatus }) => originalStatus.account,
      originalAccountId: ({ originalAccount }) => originalAccount.id,
      accountForShortcut: ({ originalAccount, notification }) => notification ? notification.account : originalAccount,
      visibility: ({ originalStatus }) => originalStatus.visibility,
      plainTextContent: ({ originalStatus }) => originalStatus.plainTextContent || '',
      plainTextContentOverLength: ({ plainTextContent }) => (
        // measureText() is expensive, so avoid doing it when possible.
        // Also measureText() typically only makes text shorter, not longer, so we can measure the raw length
        // as a shortcut. (The only case where it makes text longer is with short URLs which get expanded to a longer
        // placeholder.) This isn't 100% accurate, but we don't need perfect accuracy here because this is just
        // to show a "long post" content warning.
        plainTextContent.length > LONG_POST_LENGTH && measureText(plainTextContent) > LONG_POST_LENGTH
      ),
      spoilerText: ({ originalStatus, plainTextContentOverLength }) => (
        originalStatus.spoiler_text || (plainTextContentOverLength && LONG_POST_TEXT)
      ),
      inReplyToId: ({ originalStatus }) => originalStatus.in_reply_to_id,
      uuid: ({ $currentInstance, timelineType, timelineValue, notificationId, statusId }) => (
        createStatusOrNotificationUuid($currentInstance, timelineType, timelineValue, notificationId, statusId)
      ),
      elementId: ({ uuid }) => uuid,
      shortcutScope: ({ elementId }) => elementId,
      isStatusInOwnThread: ({ timelineType, timelineValue, originalStatusId }) => (
        (timelineType === 'status' || timelineType === 'reply') && timelineValue === originalStatusId
      ),
      isStatusInNotification: ({ originalStatusId, notification }) => (
        notification && notification.status &&
          notification.type !== 'mention' && notification.status.id === originalStatusId
      ),
      spoilerShown: ({ $spoilersShown, uuid, $showAllSpoilers }) => (typeof $spoilersShown[uuid] === 'undefined' ? !!$showAllSpoilers : !!$spoilersShown[uuid]),
      replyShown: ({ $repliesShown, uuid }) => !!$repliesShown[uuid],
      showCard: ({ originalStatus, isStatusInNotification, showMedia, $hideCards }) => (
        !$hideCards &&
        !isStatusInNotification &&
        !showMedia &&
        originalStatus.card &&
        originalStatus.card.title
      ),
      showPoll: ({ originalStatus }) => (
        originalStatus.poll
      ),
      showMedia: ({ originalStatus, isStatusInNotification }) => (
        !isStatusInNotification &&
        originalStatus.media_attachments &&
        originalStatus.media_attachments.length
      ),
      mediaAttachments: ({ originalStatus }) => (
        originalStatus.media_attachments
      ),
      sensitiveShown: ({ $sensitivesShown, uuid }) => !!$sensitivesShown[uuid],
      sensitive: ({ originalStatus, $markMediaAsSensitive, $neverMarkMediaAsSensitive }) => (
        !$neverMarkMediaAsSensitive && ($markMediaAsSensitive || originalStatus.sensitive)
      ),
      originalAccountEmojis: ({ originalAccount }) => (originalAccount.emojis || []),
      originalStatusEmojis: ({ originalStatus }) => (originalStatus.emojis || []),
      originalAccountDisplayName: ({ originalAccount }) => (originalAccount.display_name || originalAccount.username),
      originalAccountAccessibleName: ({ originalAccount, $omitEmojiInDisplayNames }) => {
        return getAccountAccessibleName(originalAccount, $omitEmojiInDisplayNames)
      },
      createdAtDate: ({ originalStatus }) => originalStatus.created_at,
      createdAtDateTS: ({ createdAtDate }) => new Date(createdAtDate).getTime(),
      absoluteFormattedDate: ({ createdAtDateTS }) => absoluteDateFormatter().format(createdAtDateTS),
      shortInlineFormattedDate: ({ createdAtDateTS, $now, $disableRelativeTimestamps }) => (
        $disableRelativeTimestamps
          ? dayOnlyAbsoluteDateFormatter().format(createdAtDateTS)
          : formatTimeagoDate(createdAtDateTS, $now)
      ),
      reblog: ({ status }) => status.reblog,
      ariaLabel: ({
        originalAccount, account, plainTextContent, shortInlineFormattedDate, spoilerText,
        showContent, reblog, notification, visibility, $omitEmojiInDisplayNames, $disableLongAriaLabels,
        showMedia, sensitive, sensitiveShown, mediaAttachments, showPoll
      }) => (
        getAccessibleLabelForStatus(originalAccount, account, plainTextContent,
          shortInlineFormattedDate, spoilerText, showContent,
          reblog, notification, visibility, $omitEmojiInDisplayNames, $disableLongAriaLabels,
          showMedia, sensitive, sensitiveShown, mediaAttachments, showPoll
        )
      ),
      showHeader: ({ notification, status, timelineType }) => (
        (notification && ['reblog', 'favourite', 'poll', 'status', 'update'].includes(notification.type)) ||
        status.reblog ||
        timelineType === 'pinned'
      ),
      className: ({ visibility, timelineType, isStatusInOwnThread, $underlineLinks, $disableTapOnStatus }) => (classname(
        'status-article',
        'shortcut-list-item',
        'focus-fix',
        timelineType !== 'direct' && visibility === 'direct' && 'status-direct',
        timelineType !== 'search' && 'status-in-timeline',
        isStatusInOwnThread && 'status-in-own-thread',
        $underlineLinks && 'underline-links',
        !$disableTapOnStatus && !isStatusInOwnThread && 'tap-on-status'
      )),
      content: ({ originalStatus }) => originalStatus.content || '',
      showContent: ({ spoilerText, spoilerShown }) => !spoilerText || spoilerShown,
      // These timestamp params may change every 10 seconds due to now() polling, so keep them
      // separate from the generic `params` list to avoid costly recomputes.
      timestampParams: ({ createdAtDate, createdAtDateTS, shortInlineFormattedDate, absoluteFormattedDate }) => ({
        createdAtDate,
        createdAtDateTS,
        shortInlineFormattedDate,
        absoluteFormattedDate
      }),
      // This params list deliberately does *not* include `spoilersShown` or `replyShown`, because these
      // change frequently and would therefore cause costly recomputes if included here.
      // The main goal here is to avoid typing by passing as many params as possible to child components.
      params: ({
        notification, notificationId, status, statusId, timelineType,
        account, accountId, uuid, isStatusInNotification, isStatusInOwnThread,
        originalAccount, originalAccountId, visibility,
        replyVisibility, spoilerText, originalStatus, originalStatusId, inReplyToId,
        enableShortcuts, shortcutScope, originalStatusEmojis
      }) => ({
        notification,
        notificationId,
        status,
        statusId,
        timelineType,
        account,
        accountId,
        uuid,
        isStatusInNotification,
        isStatusInOwnThread,
        originalAccount,
        originalAccountId,
        visibility,
        replyVisibility,
        spoilerText,
        originalStatus,
        originalStatusId,
        inReplyToId,
        enableShortcuts,
        shortcutScope,
        originalStatusEmojis
      })
    }
  }
</script>
